package com.fenghongzhang.day008;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //存值,取值.
        /**
         * 1,文件名称
         * 2.文件的访问方式
         */
        SharedPreferences user = getSharedPreferences("user", MODE_PRIVATE);

        //打开一个编译器
        SharedPreferences.Editor edit = user.edit();
        edit.putString("name","大明");
        edit.putBoolean("isMan",true);
        edit.putFloat("slary",100.1f);
        edit.putLong("big",10000000);
        edit.putInt("age",20);

        //提交
        edit.commit();
    }

    public void btn(View view) {
        SharedPreferences user = getSharedPreferences("user", MODE_PRIVATE);
        //1,key
        //2,默认值.当key值不存在的时候,给一个默认值
        String name = user.getString("nane","100");
        Log.i(TAG, "btn: "+name);
        String name1 = user.getString("name","200");
        Log.i(TAG, "btn: "+name1);


        boolean isMan = user.getBoolean("isMan", false);
        float slary = user.getFloat("slary", 200.0f);


    }

    public void write(View view) {
//        FileOutputStream fileOutputStream = new FileOutputStream("路径");
        try {
            FileOutputStream fileOutputStream = openFileOutput("one.txt", MODE_PRIVATE);
            fileOutputStream.write("哈哈".getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void read(View view) {
        try {
            FileInputStream fileInputStream = openFileInput("one.txt");

            int len = 0;
            byte[] bytes = new byte[1024];
            while((len = fileInputStream.read(bytes)) != -1){
                String s = new String(bytes, 0, len);
                Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
            }


            fileInputStream.close();



        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
